<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="chat.css">
    <script src="node_modules/vue/dist/vue.min.js"></script>
</head>
<body>
<div id="app">
    <div class="body">
        <ul>
            <li v-for="item in chat_list">
                <div>{{ item.username }}</div>
                <div>{{ item.message }}</div>
            </li>
        </ul>
    </div>
    <div class="navbar">
        <a class="btn btn-danger" href="index.html">返回</a>
        <button class="btn btn-light" type="button">历史消息</button>
        <button class="btn btn-success" type="button">语音输入</button>
        <div class="input-group">
            <input type="text" class="form-control" v-model="message">
            <div class="input-group-append">
                <button class="btn btn-primary" type="button" v-on:click="send_message">发送</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    const server_ip = window.android.get_pref('server_ip');
    const port = window.android.get_pref('port');
    const cur_username = window.android.get_current_username();
    var websocketUrl = `ws://${server_ip}:${port}?username=${cur_username}`;
    var ws = null;
    if (window.WebSocket !== undefined) {
        if (server_ip === '' || port === '') {
            window.android.show_toast_long('WebSocket服务器URL为空，请前往设置');
        } else {
            ws = new WebSocket(websocketUrl);
            ws.onclose = function () {
                window.android.show_toast_short('连接已断开');
            }
            ws.onerror = function (e) {
                console.log(e);
                window.android.show_toast_long('WebSocket服务器连接出错');
            }
            ws.onmessage = function (e) {
                var knife_index = e.data.indexOf(',');
                if (knife_index > -1) {
                    const command = e.data.substring(0, knife_index);
                    const msg = e.data.substring(knife_index + 1);
                    if (command === target_username) {
                        chat_list.push({
                            username: command,
                            message: msg
                        });
                        window.android.save_history(1, command, msg);
                    } else if (command === 'error') {
                        window.android.show_toast_long('WebSocket服务器连接出错，错误信息：' + msg);
                    }
                }
            }
        }
    }
    if (location.href.indexOf('?') === -1) {
        location.href = 'index.html';
    }
    const get_array = location.href.split('?')[1].split('&');
    var get_dict = {};
    for (var i in get_array) {
        var get = get_array[i].split('=');
        get_dict[get[0]] = get[1];
    }
    var target_username = get_dict['target'].replace(/%20/g, ' ');
    var chat_str = window.android.get_chat_history(target_username, 10);
    var chat_list = [];
    if (chat_str !== '') {
        var chat_array = chat_str.split('{{|}}');
        for (var i in chat_array) {
            var item = chat_array[i];
            var item_array = item.split('{{||}}');
            chat_list.push({
                username: item_array[0].replace(/%20/g, ' '),
                message: item_array[2]
            });
        }
    }
    const current_username = window.android.get_current_username();
    new Vue({
        el: '#app',
        data: {
            chat_list: chat_list,
            message: ''
        },
        methods: {
            send_message() {
                if (this.message === '') {
                    window.android.show_toast_long('消息不能为空');
                    return;
                } else if (this.message.indexOf('{{|}}') !== -1 ||
                    this.message.indexOf('{{||}}') !== -1) {
                    window.android.show_toast_long('消息中含有非法字符串');
                }
                window.android.save_history(0, target_username, this.message);
                ws.send(`${current_username},${target_username},${this.message}`);
                this.chat_list.push({
                    username: '我',
                    message: this.message
                });
                this.message = '';
            }
        }
    });
</script>
</body>
</html>
